package com.may.wlrj.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.may.wlrj.entity.UserEntity;
import com.may.wlrj.entity.UserLogEntity;
import com.may.wlrj.services.LockService;
import com.may.wlrj.services.LogUionService;
import com.may.wlrj.util.ReadExcel;
import com.may.wlrj.util.XinLongUtil;


@Controller
public class FileupdowController {
	    
    private LockService lockService;
	
    @Autowired
    public void setLockService(LockService lockService){
        this.lockService = lockService;
    }
    
    private LogUionService loguionService;
	
    @Autowired
    public void setLogUionService(LogUionService loguionService){
        this.loguionService = loguionService;
    }
    
    @RequestMapping(value="/upload",method=RequestMethod.POST,produces="application/json;charset=UTF-8;")
	@ResponseBody //不写会默认返回当前路径！！
	public DeferredResult<String> upload(HttpServletRequest req, HttpSession session) throws Exception, IOException{

		//接收文件数据
    	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        
        // 获取上传的文件
        MultipartFile multiFile = multipartRequest.getFile("file");
		System.out.println(multiFile.getContentType());//  image/jpeg   获取上传文件的类型
		System.out.println(multiFile.getName());//image  获取file标签的name属性  <input type="file" name="image" >
		System.out.println(multiFile.getOriginalFilename());//1.jpg   获取上传文件的名称
		ObjectMapper mapper = new ObjectMapper(); 
		ObjectNode resjson = mapper.createObjectNode();  
		
		//获取到上传的文件数据
		String contentType = multiFile.getContentType();
		DeferredResult<String> deferredResult = new DeferredResult<String>();
		
		//判断上传文件是否为图片
		if (contentType==null||!contentType.startsWith("application/")) {
			System.out.println("===不属于图片类型...===");
			resjson.put("status", "1");
			resjson.put("desc", "不属于EXCEL文件类型");
			String res = mapper.writeValueAsString(resjson);  
			deferredResult.setResult(res);
			return deferredResult;
		}
		
		//动态获取上传文件夹的路径
		ServletContext context = req.getServletContext();
		String realPath = context.getRealPath("/upload");//获取本地存储位置的绝对路径
		
		String filename = multiFile.getOriginalFilename();//获取上传时的文件名称
		dealInOtherThread(deferredResult,multiFile,realPath,filename,req,session);
		
		return deferredResult;
		
	}
    
    private void dealInOtherThread(DeferredResult<String> deferredResult,MultipartFile image,String realPath,String filename,HttpServletRequest request, HttpSession session) throws JsonProcessingException {
    	String res = "";
    	File f= new File(realPath, filename);
		try {
			//Thread.sleep(300000);
			image.transferTo(f);//将上传的文件存储到指定位置
			res = lockService.regImport(realPath+"/" + filename, request, session);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
    	
    	 
    	deferredResult.setResult(res);
    }
	
	/*
	 * 下载方式一：
	 * ①获取前台要下载的文件名称
	 * ②设置响应类型
	 * ③设置下载页显示的文件名
	 * ④获取下载文件夹的绝对路径和文件名合并为File类型
	 * ⑤将文件复制到浏览器
	 */
	@RequestMapping("/download")
	@ResponseBody
	public void download(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws Exception {
		System.out.println("===download===");
		try {
	    	   //得到要下载的文件名
	           String fileName = "app.apk";
	           String fileSaveRootPath=req.getSession().getServletContext().getRealPath("/download");
	           //文件路径
	           File file = new File(fileSaveRootPath + "\\" + fileName);
	           //如果文件不存在
	           if(!file.exists()){
	               System.out.println("您要下载的资源已被删除！！");
	               return;
	           }
	           //设置响应头，控制浏览器下载该文件
	           resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
	    	   InputStream fis = new BufferedInputStream(new FileInputStream(fileSaveRootPath + "\\" + fileName));
	           byte[] buffer = new byte[fis.available()]; 
	           fis.read(buffer);  //读取文件流
	           fis.close();//关闭文件流
	           resp.reset();//重置结果集
	           resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
	           resp.addHeader("Content-Length", "" + file.length());  //返回头 文件大小
	           resp.setContentType("application/octet-stream");    //设置数据种类
	           ///获取返回体输出权
	           OutputStream os = new BufferedOutputStream(resp.getOutputStream());  
	           // 输出文件
	           os.write(buffer);
	           os.flush();
	           os.close();
	       } catch (IOException e) {
	    	   e.printStackTrace();
	       } 
	}
	
	@RequestMapping(value="/plugins_download")
	@ResponseBody
	public void plugins_download(String filename,HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws Exception {
		System.out.println("===download===" + filename);
		try {
	    	   //得到要下载的文件名
	           String fileSaveRootPath=req.getSession().getServletContext().getRealPath("/download");
	           //文件路径
	           File file = new File(fileSaveRootPath + "\\" + filename);
	           //如果文件不存在
	           if(!file.exists()){
	               System.out.println("您要下载的资源已被删除！！");
	               return;
	           }
	           //设置响应头，控制浏览器下载该文件
	           resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
	    	   InputStream fis = new BufferedInputStream(new FileInputStream(fileSaveRootPath + "\\" + filename));
	           byte[] buffer = new byte[fis.available()]; 
	           fis.read(buffer);  //读取文件流
	           fis.close();//关闭文件流
	           resp.reset();//重置结果集
	           resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
	           resp.addHeader("Content-Length", "" + file.length());  //返回头 文件大小
	           resp.setContentType("application/octet-stream");    //设置数据种类
	           ///获取返回体输出权
	           OutputStream os = new BufferedOutputStream(resp.getOutputStream());  
	           // 输出文件
	           os.write(buffer);
	           os.flush();
	           os.close();
	       } catch (IOException e) {
	    	   e.printStackTrace();
	       } 
	}	
	
	@RequestMapping(value="usermanagerlog_download",produces="text/html;charset=UTF-8;") 
	@ResponseBody 
	//获取url链接上的参数
	public DeferredResult<String> usermanagerlog_download(HttpServletResponse response,HttpSession session,HttpServletRequest request,@RequestParam("start") String start,@RequestParam("end") String end,@RequestParam("orgname") String orgname) throws JsonProcessingException{
	      response.setContentType("application/binary;charset=UTF-8");
	      UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
	      DeferredResult<String> deferredResult = new DeferredResult<String>();

	      Date date = new Date();
		  SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	      String remoteaddr = XinLongUtil.getRemoteAddr(request);
	      UserLogEntity ulog = new UserLogEntity();
		  ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		  ulog.setRemote_addr(remoteaddr);
		  ulog.setCreatetime(dateFormat.format(date));
		  ulog.setArgs_json("");
		  ulog.setRname("系统管理/日志管理/日志导出");
		  ulog.setCreateusername(sentity.getUsername());
		  ulog.setUserid(sentity.getId());
		  ulog.setMethod("usermanagerlog_download");
		  dealwithUserManagerlogWriteExcel(deferredResult,response,ulog,session,start,end,orgname);
			
		  return deferredResult;
	}
	
	private void dealwithUserManagerlogWriteExcel(DeferredResult<String> deferredResult,HttpServletResponse response,UserLogEntity ulog,HttpSession session,String start,String end,String orgname){
		try{
            ServletOutputStream out=response.getOutputStream();
            Date date = new Date();
            
            try {
                //设置文件头
          	  SimpleDateFormat dateFormat2= new SimpleDateFormat("yyyy-MM-dd");
          	  response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("用户管理日志导出表" + dateFormat2.format(date) + ".xlsx", "UTF-8"));
              
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
         
            String[] titles = { "功能名称", "被操作用户", "机构名称", "经办人", "复核人", "日志时间", "备注" }; 
            try{
            	loguionService.WriteUserManagerlogToExcel(titles, out,session,start,end,orgname);
            	deferredResult.setResult("success");
            }catch(Exception ex){
            	deferredResult.setResult(ex.getMessage());
            }
            
            
        } catch(Exception e){
            e.printStackTrace();
            ulog.setDescriptor(e.getMessage());
            ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			deferredResult.setResult("error");
        }
	}
	
	@RequestMapping(value="syslog_download",produces="text/html;charset=UTF-8;") 
	@ResponseBody 
	//获取url链接上的参数
	public DeferredResult<String> syslog_download(HttpServletResponse response,HttpSession session,HttpServletRequest request,@RequestParam("start") String start,@RequestParam("end") String end,@RequestParam("orgid") String orgid,@RequestParam("searchval") String searchval,@RequestParam("searchproperty") String searchproperty) throws JsonProcessingException{
	      response.setContentType("application/binary;charset=UTF-8");
	      UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
	      DeferredResult<String> deferredResult = new DeferredResult<String>();

	      Date date = new Date();
		  SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	      String remoteaddr = XinLongUtil.getRemoteAddr(request);
	      UserLogEntity ulog = new UserLogEntity();
		  ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		  ulog.setRemote_addr(remoteaddr);
		  ulog.setCreatetime(dateFormat.format(date));
		  ulog.setArgs_json("");
		  ulog.setRname("系统管理/日志管理/日志导出");
		  ulog.setCreateusername(sentity.getUsername());
		  ulog.setUserid(sentity.getId());
		  ulog.setMethod("syslog_download");
		  dealwithSyslogWriteExcel(deferredResult,response,ulog,session,start,end,orgid,searchval,searchproperty);
			
		  return deferredResult;
	}
	
	private void dealwithSyslogWriteExcel(DeferredResult<String> deferredResult,HttpServletResponse response,UserLogEntity ulog,HttpSession session,String start,String end,String orgid,String searchval,String searchproperty){
		try{
            ServletOutputStream out=response.getOutputStream();
            Date date = new Date();
            
            try {
                //设置文件头
          	  SimpleDateFormat dateFormat2= new SimpleDateFormat("yyyy-MM-dd");
          	  response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("用户操作日志导出表" + dateFormat2.format(date) + ".xlsx", "UTF-8"));
              
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
         
            String[] titles = { "操作时间", "操作人", "IP地址", "功能名称", "所属机构"}; 
            try{
            	loguionService.WriteSyslogToExcel(titles, out,session,start,end,orgid,searchval,searchproperty);
            	deferredResult.setResult("success");
            }catch(Exception ex){
            	deferredResult.setResult(ex.getMessage());
            }
            
            
        } catch(Exception e){
            e.printStackTrace();
            ulog.setDescriptor(e.getMessage());
            ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			deferredResult.setResult("error");
        }
	}
	
	@RequestMapping(value="openlog_download",produces="text/html;charset=UTF-8;") 
	@ResponseBody 
	//获取url链接上的参数
	public DeferredResult<String> openlog_download(HttpServletResponse response,HttpSession session,HttpServletRequest request,@RequestParam("orgname") String orgname,@RequestParam("locksn") String locksn,@RequestParam("keysn") String keysn,@RequestParam("operator") String operator,@RequestParam("ckname") String ckname,@RequestParam("ckpassword") String ckpassword) throws JsonProcessingException{
	      response.setContentType("application/binary;charset=UTF-8");
	      UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
	      DeferredResult<String> deferredResult = new DeferredResult<String>();

	      Date date = new Date();
		  SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	      String remoteaddr = XinLongUtil.getRemoteAddr(request);
	      UserLogEntity ulog = new UserLogEntity();
		  ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		  ulog.setRemote_addr(remoteaddr);
		  ulog.setCreatetime(dateFormat.format(date));
		  ulog.setArgs_json("");
		  ulog.setRname("系统管理/日志管理/开锁记录导出");
		  ulog.setCreateusername(sentity.getUsername());
		  ulog.setUserid(sentity.getId());
		  ulog.setMethod("openlog_download");
		  dealwithOpenlogWriteExcel(deferredResult,response,ulog,session,orgname,locksn,keysn,operator,ckname,ckpassword);
			
		  return deferredResult;
	}
	
	private void dealwithOpenlogWriteExcel(DeferredResult<String> deferredResult,HttpServletResponse response,UserLogEntity ulog,HttpSession session,String orgname,String locksn,String keysn,String operator,String ckname,String ckpassword){
		try{
            ServletOutputStream out=response.getOutputStream();
            Date date = new Date();
            
            try {
                //设置文件头
          	  SimpleDateFormat dateFormat2= new SimpleDateFormat("yyyy-MM-dd");
          	  response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("开锁日志导出表" + dateFormat2.format(date) + ".xlsx", "UTF-8"));
              
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
         
            String[] titles = { "锁具识别码", "钥匙识别码", "开锁人", "开锁时间", "开/闭锁", "所属机构", "结果",}; 
            try{
            	loguionService.WriteOpenlogToExcel(titles, out,session,orgname,locksn,keysn,operator);
            	deferredResult.setResult("success");
            }catch(Exception ex){
            	deferredResult.setResult(ex.getMessage());
            }
            
            
        } catch(Exception e){
            e.printStackTrace();
            ulog.setDescriptor(e.getMessage());
            ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			deferredResult.setResult("error");
        }
	}
	
	@RequestMapping(value="lockofflog_download",produces="text/html;charset=UTF-8;") 
	@ResponseBody 
	//获取url链接上的参数
	public DeferredResult<String> lockofflog_download(HttpServletResponse response,HttpSession session,HttpServletRequest request,@RequestParam("ckname") String ckname,@RequestParam("ckpassword") String ckpassword,@RequestParam("orgname") String orgname,@RequestParam("locksn") String locksn) throws JsonProcessingException{
	      response.setContentType("application/binary;charset=UTF-8");
	      UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
	      DeferredResult<String> deferredResult = new DeferredResult<String>();

	      Date date = new Date();
		  SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	      String remoteaddr = XinLongUtil.getRemoteAddr(request);
	      UserLogEntity ulog = new UserLogEntity();
		  ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		  ulog.setRemote_addr(remoteaddr);
		  ulog.setCreatetime(dateFormat.format(date));
		  ulog.setArgs_json("");
		  ulog.setRname("系统管理/日志管理/锁具报废记录导出");
		  ulog.setCreateusername(sentity.getUsername());
		  ulog.setUserid(sentity.getId());
		  ulog.setMethod("lockofflog_download");
		  dealwithLockofflogWriteExcel(deferredResult,response,ulog,session,orgname,locksn,ckname,ckpassword);
			
		  return deferredResult;
	}
	
	private void dealwithLockofflogWriteExcel(DeferredResult<String> deferredResult,HttpServletResponse response,UserLogEntity ulog,HttpSession session,String orgname,String locksn,String ckname,String ckpassword){
		try{
            ServletOutputStream out=response.getOutputStream();
            Date date = new Date();
            
            try {
                //设置文件头
          	  SimpleDateFormat dateFormat2= new SimpleDateFormat("yyyy-MM-dd");
          	  response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("报废日志导出表" + dateFormat2.format(date) + ".xlsx", "UTF-8"));
              
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
         
            String[] titles = { "锁具识别码", "类型", "使用人", "所属机构", "使用区域", "使用箱号", "报废时间", "操作人", "备注",}; 
            try{
            	loguionService.WriteLockofflogToExcel(titles, out,session,orgname,locksn);
            	deferredResult.setResult("success");
            }catch(Exception ex){
            	deferredResult.setResult(ex.getMessage());
            }
            
            
        } catch(Exception e){
            e.printStackTrace();
            ulog.setDescriptor(e.getMessage());
            ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			deferredResult.setResult("error");
        }
	}
}
